home *** CD-ROM | disk | FTP | other *** search
Wrap
Here's an example of one that will work (be sure to read the tail of this answer which details when such a scheme will *not* work): /****** C/C++ header file: X.h ******/ #ifdef __cplusplus /*'__cplusplus' is #defined iff compiler is C++*/ extern "C" { #endif #ifdef __STDC__ extern int c_fn(struct X*); /* ANSI-C prototypes */ extern struct X* cplusplus_callback_fn(struct X*); #else extern int c_fn(); /* K&R style */ extern struct X* cplusplus_callback_fn(); #endif #ifdef __cplusplus } #endif #ifdef __cplusplus class X { int a; public: X(); void frob(int); }; #endif Then, in file 'X.C': //X.C #include "X.h" X::X() : a(0) { } void X::frob(int aa) { a = aa; } X* cplusplus_callback_fn(X* x) { x->frob(123); return x; } In C++ file 'main.C': #include "X.h" int main() { X x; c_fn(&x); return 0; } Finally, in a C file 'c-fn.c': /* C source file c-fn.c */ #include "X.h" int c_fn(struct X* x) { if (cplusplus_callback_fn(x)) do_one_thing(); else do_something_else(); return something(); } Passing ptrs to C++ objects to/from C fns will FAIL if you pass and get back something that isn't *exactly* the same pointer, such as passing a base class ptr and receiving a derived class ptr (this fails when multiple inheritance is involved, since C fails to do pointer-conversion properly).